import Stomp from 'stompjs';
import SockJS from 'sockjs-client';

class WebSocketService {
  constructor() {
    this.stompClient = null;
    this.connected = false;
    this.subscriptions = {};
  }

  connect() {
    if (this.connected) return;

    const socket = new SockJS('http://127.0.0.1:8080/ws-devices');
    this.stompClient = Stomp.over(socket);

    this.stompClient.connect({}, () => {
      this.connected = true;
      console.log('WebSocket 连接成功');

      // 重新订阅所有主题
      Object.keys(this.subscriptions).forEach(topic => {
        this.subscribe(topic, this.subscriptions[topic].callback);
      });
    }, (error) => {
      console.error('WebSocket 连接失败:', error);
      this.connected = false;
    });
  }

  disconnect() {
    if (this.stompClient && this.connected) {
      this.stompClient.disconnect(() => {
        console.log('WebSocket 已断开');
        this.connected = false;
      });
    }
  }

  sendControlCommand(device, command) {
    if (!this.connected) {
      console.error('无法发送命令: WebSocket 未连接');
      return false;
    }

    const message = {
      device: device,
      command: command
    };

    this.stompClient.send("/app/device/control", {}, JSON.stringify(message));
    return true;
  }

  subscribe(topic, callback) {
    if (!this.connected) {
      // 保存订阅请求，连接成功后自动订阅
      this.subscriptions[topic] = { callback };
      console.log("订阅"+topic)
      return;
    }

    const subscription = this.stompClient.subscribe(topic, (message) => {
      try {
        const parsed = JSON.parse(message.body);
        callback(parsed);
      } catch (e) {
        console.error('消息解析失败:', e);
      }
    });

    this.subscriptions[topic] = {
      callback,
      subscription
    };
  }

  unsubscribe(topic) {
    if (this.subscriptions[topic]) {
      if (this.subscriptions[topic].subscription) {
        this.subscriptions[topic].subscription.unsubscribe();
      }
      delete this.subscriptions[topic];
    }
  }
}

// 创建单例实例
const webSocketService = new WebSocketService();

// 应用启动时自动连接
webSocketService.connect();

// 页面关闭时断开连接
window.addEventListener('beforeunload', () => {
  webSocketService.disconnect();
});

export default webSocketService;
